﻿using System;
using System.Collections.Generic;
using System.Threading;
using System.Windows.Forms;

namespace ChatGUI
{
    public partial class MainForm : Form
    {
        private Chat chat;

        public MainForm(Chat chat)
        {
            this.chat = chat;
            InitializeComponent();
            this.Icon = sinetd.Utilities.Assembly.GetIconLarge(sinetd.Utilities.Process.GetExeName(), 0);

            chat.MessageRecv += new Chat.MessageHandler(chat_MessageRecv);
        }

        private void AddToListBoxTS(ListBox listBox, string msg)
        {
            listBox.Invoke(new Action(() =>
            {
                if (!this.IsDisposed)
                {
                    listBox.Items.Add(msg);
                }
            }));
        }

        private void chat_MessageRecv(string msg)
        {
            AddToListBoxTS(listBox_msg, msg);
        }

        private void button_send_Click(object sender, System.EventArgs e)
        {
            new Thread(() =>
            {
                try
                {
                    if (chat.SendMsg(textBox_msg.Text))
                    {
                        textBox_msg.Invoke(new Action(() =>
                        {
                            textBox_msg.Text = "";
                        }));
                    }
                }
                catch (Exception ex)
                {
                    AddToListBoxTS(listBox_msg, ex.Message);
                }
            }).Start();
        }

        private void button_refresh_list_Click(object sender, EventArgs e)
        {
            listBox_who.Items.Clear();
            new Thread(() =>
            {
                List<string> list = chat.Who();

                foreach (string name in list)
                {
                    AddToListBoxTS(listBox_who, name);
                }
            }).Start();
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            chat.Dispose();
        }
    }
}
